package com.idp.web.test.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.idp.common.base.BaseController;
import com.idp.common.persistence.Page;
import com.idp.common.util.ExcelUtil;
import com.idp.common.util.FileUtils;
import com.idp.common.util.ValidateUtils;
import com.idp.web.test.entity.DetailList;
import com.idp.web.test.entity.Warehouse;
import com.idp.web.test.service.DetailListService;
import com.idp.web.test.service.ProductService;
import com.idp.web.test.service.PutService;
import com.idp.web.test.service.WarehouseService;
import net.sf.json.JSONObject;

/**
 * 
 * 出入库明细controller
 * 
 * <pre>
 * 	历史记录：
 * 	2017-06-06 Amber
 * 	新建文件
 * </pre>
 * 
 * @author
 * 
 * 		<pre>
 * SD
 * 	Amber
 * PG
 *	Amber
 * UT
 *
 * MA
 *         </pre>
 * 
 * @version $Rev$
 *
 *          <p/>
 *          $Id$
 *
 */
@Controller
@RequestMapping("/detailList")
public class DetailListController extends BaseController {

	private Logger logger = Logger.getLogger(DetailListController.class);

	@Resource
	private DetailListService detailListService;
	@Resource
	private WarehouseService warehouseService;
	@Resource
	private PutService putService;
	@Resource
	private ProductService productService;

	/**
	 * 
	 * <pre>
	 * 	2017-06-06 Amber
	 * 	初始化查询页面
	 * </pre>
	 * 
	 * @return
	 */
	@RequestMapping("/init")
	public String init(HttpServletRequest request) {
		try {
			request.setAttribute("warehouse", warehouseService.findBySearch(new Warehouse()));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shopping/detailList/detailListSearch";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-06 Amber
	 * 	分页查询
	 * </pre>
	 * 
	 * @param detailList
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping("/putList")
	public String putList(Integer warehouseId, String productName, String beginTime, String endTime,
			Page<DetailList> page, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		map.put("coulmnSql", "put_id");
		map.put("tableName", "put");
		try {
			page.setFuncName("putListPage");
			if (warehouseId == 0) {
				warehouseId = null;
			}
			map.put("warehouseId", warehouseId);
			map.put("productName", productName);
			map.put("beginTime", beginTime);
			map.put("endTime", endTime);
			request.setAttribute("putDetail", detailListService.findByTips(map, page));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shopping/detailList/detailListPut";
	}

	@RequestMapping("/outList")
	public String outList(Integer warehouseId, String productName, String beginTime, String endTime,
			Page<DetailList> page, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		map.put("coulmnSql", "out_id");
		map.put("tableName", "outs");
		try {
			page.setFuncName("putListPage");
			if (warehouseId == 0) {
				warehouseId = null;
			}
			map.put("warehouseId", warehouseId);
			map.put("productName", productName);
			map.put("beginTime", beginTime);
			map.put("endTime", endTime);
			request.setAttribute("outDetail", detailListService.findByTips(map, page));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shopping/detailList/detailListOut";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-06 Amber
	 * 	新增修改页面初始化
	 * </pre>
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/detailList")
	public String detailList(Integer id, HttpServletRequest request) {
		try {
			if (ValidateUtils.isNotEmpty(id)) {
				DetailList detailList = detailListService.getById(id);
				request.setAttribute("detailList", detailList);
			}
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
		}

		return "test/detailList";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-06 Amber
	 * 	保存
	 * </pre>
	 * 
	 * @param detailList
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(DetailList detailList) {
		JSONObject json = new JSONObject();
		try {
			// 修改
			if (ValidateUtils.isNotEmpty(detailList.getId())) {
				detailListService.update(detailList);
			}
			// 新增
			else {
				detailListService.add(detailList);
			}
			json.put("result", "save_success");
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
			json.put("result", "save_fail");
		}

		return json.toString();
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-06 Amber
	 * 	删除
	 * </pre>
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(Integer id) {
		JSONObject json = new JSONObject();
		try {
			detailListService.delete(id);
			json.put("result", "delete_success");
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
			json.put("result", "delete_fail");
		}

		return json.toString();
	}

	/**
	 * 批量导出明细
	 * 
	 * @param warehouseId
	 * @param typeId
	 * @param beginTime
	 * @param endTime
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("batchExport")
	public String batchExport(Integer warehouseId, Integer typeId, String beginTime, String endTime,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<>();
		map.put("warehouseId", warehouseId);
		map.put("productName", null);
		map.put("beginTime", beginTime);
		map.put("endTime", endTime);
		Warehouse warehouse = warehouseService.getById(warehouseId);
		String type = null;
		switch (typeId) {
		case 0:
			type = "出入库";
			break;
		case 1:
			type = "入库";
			map.put("coulmnSql", "put_id");
			map.put("tableName", "put");
			break;
		case 2:
			type = "出库";
			map.put("coulmnSql", "out_id");
			map.put("tableName", "outs");
			break;
		default:
			type = "未知";
			break;
		}
		Map<String, List<DetailList>> mapList = new HashMap<>();
		List<DetailList> detailLists = null;
		HSSFWorkbook workbook = null;

		if (typeId == 0) { // 当选择所有时
			// 入库
			map.put("coulmnSql", "put_id");
			map.put("tableName", "put");
			detailLists = detailListService.findByTips(map);
			mapList.put("入库", detailLists);
			// 出库
			map.put("coulmnSql", "out_id");
			map.put("tableName", "outs");
			List<DetailList> detailListsOut = detailListService.findByTips(map);
			mapList.put("出库", detailListsOut);
		} else { // 当选择某一类别时
			detailLists = detailListService.findByTips(map);
			map.put(type, detailLists);
		}
		workbook = ExcelUtil.creatDetailList(type, mapList);

		// --------------------------- //
		String fileName = warehouse.getName() + "-" + type + "-" + beginTime + "至" + endTime;
		fileName = FileUtils.encodingFileName(fileName);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			workbook.write(os);
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// 设置reponse参数,打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
			ServletOutputStream sos = response.getOutputStream();
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(sos);
			byte[] buff = new byte[2048];
			int bytesRead = 0;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				bis.close();
			}
			if (bos != null) {
				bos.close();
			}
		}
		return null;
	}
}
